﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ChatClient.ServiceReference1;
using Microsoft.Win32;
using System.IO;
using System.Threading;

namespace ChatClient
{
    /// <summary>
    /// ClientWindow.xaml 的交互逻辑
    /// </summary> , UseSynchronizationContext = false
    /// 这里面的代码会形成死锁（所以我们这里设置 ConcurrencyMode 来解决死锁问题）---- 调用主线程的 UI 的时候会报错
    /// ConcurrencyMode 的三个属性 Multiple 可以是的多个线程访问，Reentrant 一个线程多次访问，Single 就是单次访问
    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple )]
    public partial class ClientWindow : Window, IChatServiceCallback

    {

        //List<Socket> ClientProxSocketList = new List<Socket>();
        public ClientWindow()
        {
            InitializeComponent();
            this.Closing += ClientWindow_Closing;
            dockPanel1.Visibility = System.Windows.Visibility.Hidden;
        }

        public string UserName
        {
            get { return textBoxUserName.Text; }
            set { textBoxUserName.Text = value; }
        }
        private ChatServiceClient client;

        void ClientWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        { 
            if (client != null)
            {
                client.Logout(UserName); //退出

                // 退出操作进行之后，我们更新用户数量

                //OnlineUserNum.Text = "在线用户（" + client.Count().ToString() + ")";

                client.Close();


            }
        }

        private void AddMessage(string str)
        {
            TextBlock t = new TextBlock();
            t.Text = str;
            t.Foreground = Brushes.Blue;
            listBoxMessage.Items.Add(t);
        }
        private void AddPng(byte[] msg)
        {
            

        }

        //单击登录按钮引发的事件
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            UserName = textBoxUserName.Text;
            InstanceContext context = new InstanceContext(this);
            client = new ServiceReference1.ChatServiceClient(context);
            try
            {
                if (client.IsRepeat(UserName))
                {
                    MessageBox.Show("当前用户名已存在，请重新输入！！！");
                    return;
                }
                else
                {
                    // 登陆操作进行之后，我们更新用户数量

                    client.Login(textBoxUserName.Text);
                    btnLogin.IsEnabled = false;


                    Thread.Sleep(100);
                    Thread t1 = new Thread(ShowTotalNum);
                    t1.Start();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("与服务端连接失败：" + ex.Message);
                return;
            }
            this.Cursor = Cursors.Arrow;

        }


        // 显示在线用户总数的方法
        public void ShowTotalNum()
        {
            string count = client.Count();

            OnlineUserNum.Dispatcher.Invoke(() =>
            {
                OnlineUserNum.Text = client.Count().ToString() + "人";
            });
        }

        //单击发送按钮引发的事件
        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            client.Talk(UserName, textBoxTalk.Text);
            textBoxTalk.Text = "";
        }

        //在文本框中输入对话后按回车键时引发的事件
        private void textBoxTalk_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                client.Talk(UserName, textBoxTalk.Text);
                textBoxTalk.Text = "";
            }
        }

        #region 实现IRndGameServiceCallback接口
        /// <summary>有用户登录</summary>
        public void ShowLogin(string loginUserName)
        {
            if (loginUserName == UserName)
            {
                dockPanel1.Visibility = System.Windows.Visibility.Visible;
            }
            listBoxOnLine.Items.Add(loginUserName);

            Thread.Sleep(100);
            Thread t1 = new Thread(ShowTotalNum);
            t1.Start();
        }

        /// <summary>其他用户退出</summary>
        public void ShowLogout(string userName)
        {
            listBoxOnLine.Items.Remove(userName);

            Thread.Sleep(100);
            Thread t1 = new Thread(ShowTotalNum);
            t1.Start();
        }

        public void ShowTalk(string userName, string message)
        {

            AddMessage(string.Format("[{0}]说：{1} ", userName, message));

        }

        public void InitUsersInfo(string UsersInfo)
        {
            if (UsersInfo.Length == 0) return;
            string[] users = UsersInfo.Split('、');
            for (int i = 0; i < users.Length; i++)
            {
                listBoxOnLine.Items.Add(users[i]);
            }
        }
        #endregion

        // 文件传输

        private void btnSendFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            {
                if (ofd.ShowDialog() == DialogResult)
                {
                    return;
                }
                if (ofd.FileName == null || ofd.FileName == "") return;
                byte[] data = File.ReadAllBytes(ofd.FileName);
                client.Send(UserName, data);
            }
            
        }
        public void ShowFile(string userName, byte[] msg)
        {
            File.WriteAllBytes("C:\\Users\\17946\\Desktop\\2.png", msg);
            AddMessage(string.Format("[{0}]说：{1}", userName, "图片"));
        }
        public void ProcessReceiveFile(byte[] data)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            {
                if (sfd.ShowDialog() != DialogResult)
                {
                    return;
                }
                byte[] fileData = new byte[data.Length - 1];
                Buffer.BlockCopy(data, 1, fileData, 0, data.Length - 1);
                File.WriteAllBytes(sfd.FileName, fileData);
            }
        }
    }
}
